package com.yonyou.brigade.basic_init.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yonyou.brigade.basic_init.dao.BriChannelMapper;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.basic_init.enums.OpenTypeEnum;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.model.IChannelConfig;
import com.yonyou.brigade.basic_init.service.IBaseDocService;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.ybzboot.starter.common.exception.BaseException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jiangzhf@yonyou.com
 * @since 2018-06-06
 */
@Service
public class BriChannelServiceImpl extends ServiceImpl<BriChannelMapper, BriChannel> implements IBriChannelService {

    @Autowired
    private BriChannelMapper briChannelMapper;

    @Autowired
    @Qualifier("baseDocServiceImpl")
    private IBaseDocService baseDocService;

    @Override
    public List<BriChannel> getEnableChannelByEnable() {
        Wrapper<BriChannel> briChannelWrapper = new EntityWrapper<>();
        briChannelWrapper.where("enable", 1);
        List<BriChannel> briChannels = briChannelMapper.selectList(briChannelWrapper);
        return briChannels;
    }

    @Override
    public List<BriChannel> getEnableChannelByTenant(String tenant) {
        Wrapper<BriChannel> briChannelWrapper = new EntityWrapper<>();
        briChannelWrapper.where("tenant={0}", tenant);
        briChannelWrapper.andNew("enable={0}", 1);
        List<BriChannel> briChannels = briChannelMapper.selectList(briChannelWrapper);
        return briChannels;
    }

    @Override
    public List<BriChannel> getEnableChannelByOrg(String orgpk) {
        Wrapper<BriChannel> briChannelWrapper = new EntityWrapper<>();
        briChannelWrapper.where("orgpk={0}", orgpk);
        briChannelWrapper.andNew("enable={0}", 1);
        List<BriChannel> briChannels = briChannelMapper.selectList(briChannelWrapper);
        return briChannels;
    }

    @Override
    public List<BriChannel> getEnableChannelByTenantAndChannel(String tenant, String channel) {
        Wrapper<BriChannel> briChannelWrapper = new EntityWrapper<>();
        briChannelWrapper.where("tenant={0}", tenant);
        briChannelWrapper.andNew("channel={0}", channel);
        briChannelWrapper.andNew("enable={0}", 1);
        List<BriChannel> briChannels = briChannelMapper.selectList(briChannelWrapper);
        return briChannels;
    }

    @Override
    public BriChannel getEnableChannelByOrgAndChannel(String orgpk, String channel) {
        Wrapper<BriChannel> briChannelWrapper = new EntityWrapper<>();
        briChannelWrapper.where("orgpk", orgpk);
        briChannelWrapper.andNew("channel", channel);
        briChannelWrapper.andNew("enable", 1);
        List<BriChannel> briChannels = briChannelMapper.selectList(briChannelWrapper);
        if (briChannels != null && briChannels.size() > 0) {
            return briChannels.get(0);
        } else {
            return null;
        }
    }

    @Override
    public BriChannel getEnableInfoByTenantOrg(String tenant, String orgpk, String channel) {
        Wrapper<BriChannel> briChannelWrapper = new EntityWrapper<>();
        briChannelWrapper.where("tenant={0}", tenant);
        briChannelWrapper.andNew("orgpk={0}", orgpk);
        briChannelWrapper.andNew("channel={0}", channel);
        briChannelWrapper.andNew("enable={0}", 1);
        List<BriChannel> briChannels = briChannelMapper.selectList(briChannelWrapper);
        if (briChannels != null && briChannels.size() > 0) {
            return briChannels.get(0);
        } else {
            return null;
        }
    }

    @Override
    public List<BriChannel> getEnableChannelByChannel(String channel) {
        Wrapper<BriChannel> briChannelWrapper = new EntityWrapper<>();
        briChannelWrapper.where("channel={0}", channel);
        briChannelWrapper.andNew("enable={0}", 1);
        List<BriChannel> briChannels = briChannelMapper.selectList(briChannelWrapper);
        return briChannels;
    }

    private void saveChannle(BriChannel briChannel) {
        //check channel
        String channel = briChannel.getChannel();
        ChannelEnum[] channelEnums = ChannelEnum.values().clone();
        List<String> channels = new ArrayList<>();
        for (ChannelEnum channelEnum : channelEnums) {
            channels.add(channelEnum.getName());
        }
        if (!channels.contains(channel)) {
            throw new BaseException(-100, "不支持的渠道类型[" + channel + "]");
        }
        Wrapper<BriChannel> briChannelWrapper = new EntityWrapper<>();
        briChannelWrapper.where("tenant={0}", briChannel.getTenant());
        briChannelWrapper.andNew("orgpk={0}", briChannel.getOrgpk());
        briChannelWrapper.andNew("channel={0}", briChannel.getChannel());
        List<BriChannel> briChannels = briChannelMapper.selectList(briChannelWrapper);
        if (briChannels != null && briChannels.size() > 0) {
            briChannelMapper.update(briChannel, briChannelWrapper);
        } else {
            briChannelMapper.insert(briChannel);
        }
    }

    @Override
    public boolean isOpen(String channel, String tenant, String org, String extJson) {
        Wrapper<BriChannel> briChannelWrapper = new EntityWrapper<>();
        List<BriChannel> briChannels = null;
        switch (channel) {
            case "rtpnr":
                briChannelWrapper.where("tenant={0}", tenant);
                briChannelWrapper.andNew("orgpk={0}", org);
                briChannelWrapper.andNew("channel={0}", channel);
                briChannels = briChannelMapper.selectList(briChannelWrapper);
                break;
            case "tuniu":
                briChannelWrapper.where("tenant={0}", tenant);
                briChannelWrapper.andNew("orgpk={0}", org);
                briChannelWrapper.andNew("channel={0}", channel);
                briChannels = briChannelMapper.selectList(briChannelWrapper);
                break;
            default:
                break;

        }
        if (briChannels != null && briChannels.size() > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public String tenantOpenChannels(String tenant, String extJson) {
        JSONObject result = new JSONObject();
        Map<String, JSONObject> jsonObjectMap = new HashMap<>();
        Wrapper<BriChannel> briChannelWrapper = new EntityWrapper<>();

        briChannelWrapper.where("tenant={0}", tenant);
        briChannelWrapper.orderBy(true, "channel");
        List<BriChannel> briChannels = briChannelMapper.selectList(briChannelWrapper);
        if (briChannels != null && briChannels.size() > 0) {
            for (int i = 0; i < briChannels.size(); i++) {
                BriChannel channel = briChannels.get(i);
                if (jsonObjectMap.containsKey(channel.getChannel())) {
                    JSONObject jsonObject = jsonObjectMap.get(channel.getChannel());
                    jsonObject.put(channel.getOrgpk(), channel.getEnable());
                } else {
                    if (ChannelEnum.CTRIPSME.getName().equals(channel.getChannel())) {
                        JSONObject newChannel = new JSONObject();
                        newChannel.put("isPreApprove", channel.getIsPreApprove());
                        jsonObjectMap.put(channel.getChannel(), newChannel);
                    } else if (ChannelEnum.CTRIPBC.getName().equals(channel.getChannel())){
                        JSONObject configJSON = JSON.parseObject(channel.getConfig());
                        configJSON.put("isPreApprove", 1);
                        jsonObjectMap.put(channel.getChannel(), configJSON);
                    } else {
                        JSONObject newChannel = new JSONObject();
                        newChannel.put(channel.getOrgpk(), channel.getEnable());
                        jsonObjectMap.put(channel.getChannel(), newChannel);
                    }
                }
            }
        }
        if (jsonObjectMap.size() > 0) {
            for (Map.Entry<String, JSONObject> entry : jsonObjectMap.entrySet()) {
                result.put(entry.getKey(), entry.getValue());
            }
        }
        return result.toJSONString();
    }

    @Override
    public void openBriChannel(String tenant, String channel, int preApprove, String orgPk, OpenTypeEnum openType, String phone, IChannelConfig config) {
        BriChannel briChannel = new BriChannel();
        briChannel.setTenant(tenant);
        briChannel.setChannel(channel);
        briChannel.setEnable(1);
        briChannel.setIsPreApprove(preApprove);
        briChannel.setOrgpk(orgPk);
        briChannel.setOpenType(openType.getIndex());
        String configJson = "";
        if (config == null) {
            configJson = "{}";
        } else {
            configJson = JSONObject.toJSONString(config);
        }
        briChannel.setConfig(configJson);
        briChannel.setPhone(phone);
        saveChannle(briChannel);
    }

    //add --du
    @Override
    public void openBriChannel(BriChannel briChannel, OpenTypeEnum openType) {
        BriChannel briChannel1 = briChannel;
        briChannel1.setEnable(1);
        briChannel1.setOpenType(openType.getIndex());
        String configJson = "";
        if (briChannel.getConfig() == null) {
            configJson = "{}";
        } else {
            configJson = briChannel.getConfig();
        }
        briChannel.setConfig(configJson);
        saveChannle(briChannel1);
    }

    @Override
    public IChannelConfig getChannelConfig(String tenant, String channel, int preApprove, String orgPk, int enable, OpenTypeEnum openTypeEnum, IChannelConfig channelConfig) {
        IChannelConfig channelConfigResult = null;
        Wrapper<BriChannel> briChannelWrapper = new EntityWrapper<>();
        briChannelWrapper.where("channel={0}", channel);
        if (enable == 0 || enable == 1) {
            briChannelWrapper.andNew("enable={0}", enable);
        }
        briChannelWrapper.andNew("tenant={0}", tenant);
        if (preApprove == 0 || preApprove == 1) {
            briChannelWrapper.andNew("is_pre_approve={0}", preApprove);
        }
        if (!StringUtils.isEmpty(orgPk)) {
            briChannelWrapper.andNew("orgpk={0}", orgPk);
        }
        if (openTypeEnum.getIndex() != OpenTypeEnum.NOLIMITE.getIndex()) {
            briChannelWrapper.andNew("open_type={0}", openTypeEnum.getIndex());
        }
        List<BriChannel> briChannels = briChannelMapper.selectList(briChannelWrapper);
        String configJson = "";
        if (briChannels != null && briChannels.size() > 0) {
            configJson = briChannels.get(0).getConfig();
        }
        if (!StringUtils.isEmpty(configJson)) {
            channelConfigResult = JSONObject.parseObject(configJson, channelConfig.getClass());
        }
        return channelConfigResult;
    }

    @Override
    public IChannelConfig getChannelConfig(String tenant, String channel, String orgPk, int enable, IChannelConfig channelConfig) {
        return getChannelConfig(tenant, channel, -1, orgPk, enable, OpenTypeEnum.NOLIMITE, channelConfig);
    }

    @Override
    public IChannelConfig getChannelConfig(String tenant, String channel, String orgPk, IChannelConfig channelConfig) {
        return getChannelConfig(tenant, channel, orgPk, 1, channelConfig);
    }

    @Override
    public IChannelConfig getChannelConfig(String tenant, String channel, IChannelConfig channelConfig) {
        return getChannelConfig(tenant, channel, "", 1, channelConfig);
    }

    @Override
    public List<BriChannel> getDistinctEnableChannelGroupByTenant() {
        Wrapper<BriChannel> briChannelWrapper = new EntityWrapper<>();
        briChannelWrapper.where("enable", 1);
        briChannelWrapper.groupBy("tenant");
        List<BriChannel> briChannels = briChannelMapper.selectList(briChannelWrapper);
        return briChannels;
    }

    @Override
    public BriChannel getEnableChannelByPersonTenantOrgAndChannel(String tenant, String orgPK, String channel) {
        List<BriChannel> briChannelList = getEnableChannelByTenantAndChannel(tenant, channel);
        if (briChannelList != null && briChannelList.size() > 0 && StringUtils.isNotEmpty(orgPK)) {
            for (BriChannel briChannel : briChannelList) {
                if (briChannel.getOpenType() == 2 && orgPK.equals(briChannel.getOrgpk())) {
                    return briChannel;
                }
            }
        }
        return getEnableChannelByOpenType(tenant, channel, 1);
    }

    @Override
    public BriChannel getEnableChannelByOpenType(String tenant, String channel, int openType) {
        Wrapper<BriChannel> briChannelWrapper = new EntityWrapper<>();
        briChannelWrapper.where("tenant={0}", tenant);
        briChannelWrapper.andNew("channel={0}", channel);
        briChannelWrapper.andNew("open_type={0}", openType);
        briChannelWrapper.andNew("enable={0}", 1);
        List<BriChannel> briChannels = briChannelMapper.selectList(briChannelWrapper);
        if (briChannels != null && briChannels.size() > 0) {
            return briChannels.get(0);
        } else {
            return null;
        }
    }

    @Override
    public List<BriChannel> getEnableChannelByChannelAndOpenType(String tenant, String channel, int openType) {
        Wrapper<BriChannel> briChannelWrapper = new EntityWrapper<>();
        briChannelWrapper.where("tenant={0}", tenant);
        briChannelWrapper.andNew("channel={0}", channel);
        briChannelWrapper.andNew("open_type={0}", openType);
        briChannelWrapper.andNew("enable={0}", 1);
        List<BriChannel> briChannels = briChannelMapper.selectList(briChannelWrapper);
        return briChannels;
    }

    @Override
    public List<BriChannel> getEnableChannelByOpenTypeAndTenant(String tenant, int openType) {
        Wrapper<BriChannel> briChannelWrapper = new EntityWrapper<>();
        briChannelWrapper.where("tenant={0}", tenant);
        briChannelWrapper.andNew("open_type={0}", openType);
        briChannelWrapper.andNew("enable={0}", 1);
        List<BriChannel> briChannels = briChannelMapper.selectList(briChannelWrapper);
        return briChannels;
    }

    @Override
    public List<BriChannel> getEnableChannelByOpenTypeAndOrgAndTenant(String tenant, String org, int openType) {
        Wrapper<BriChannel> briChannelWrapper = new EntityWrapper<>();
        briChannelWrapper.where("tenant={0}", tenant);
        if (StringUtils.isNotEmpty(org)) {
            briChannelWrapper.andNew("orgpk={0}", org);
        }
        briChannelWrapper.andNew("open_type={0}", openType);
        briChannelWrapper.andNew("enable={0}", 1);
        List<BriChannel> briChannels = briChannelMapper.selectList(briChannelWrapper);
        return briChannels;
    }

    /**
     * 根据租户查询各组织渠道是否开通，返回开通的组织和没开通的组织
     *
     * @param params
     * @return
     */
    @Override
    public JSONObject orgOpenUnopen(Map params) {

        JSONObject result = new JSONObject();
        String tenantId = params.get("tenantId").toString();
        String userId = params.get("userId").toString();
        List<Map<String, String>> orgs = baseDocService.getOrgByTenant(tenantId, userId);
        for (ChannelEnum e : ChannelEnum.values()) {
            String orgpk;
            JSONObject resultJSON = new JSONObject();
            JSONArray openJSONArray = new JSONArray();
            JSONArray unopenJSONArray = new JSONArray();
            //携程商旅和中兴商旅是按租户开通
            if ("ctripSME".equals(e.getName()) || "zteitc".equals(e.getName())) {
                if (this.getEnableChannelByTenantAndChannel(tenantId, e.getName()) != null) {
                    result.put(e.getName(), "open");
                } else {
                    result.put(e.getName(), "unopen");
                }
            } else {
                for (Map m : orgs) {
                    Iterator<Map.Entry<String, String>> it = m.entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<String, String> entry = it.next();
                        if ("id".equals(entry.getKey())) {
                            orgpk = entry.getValue();
                            if (this.getEnableChannelByPersonTenantOrgAndChannel(tenantId, orgpk, e.getName()) != null) {
                                openJSONArray.add(m);
                            } else {
                                unopenJSONArray.add(m);
                            }
                        }
                    }
                }
                resultJSON.put("open", openJSONArray);
                resultJSON.put("unopen", unopenJSONArray);
                result.put(e.getName(), resultJSON);
            }
        }
        return result;
    }

    @Override
    public List<BriChannel> getEnableChannelByChannelAndOrgs(String tenantId, JSONArray orgs, String channel) {
        return briChannelMapper.getEnableChannelByChannelAndOrgs(tenantId, orgs, channel);
    }

    @Override
    public BriChannel getEnableChannelByTenantAndOrgAndChannelAndOpenType(String tenant, String org, String channel, int openType) {
        Wrapper<BriChannel> briChannelWrapper = new EntityWrapper<>();
        briChannelWrapper.where("tenant={0}", tenant);
        briChannelWrapper.andNew("orgpk={0}", org);
        briChannelWrapper.andNew("channel={0}", channel);
        briChannelWrapper.andNew("open_type={0}", openType);
        briChannelWrapper.andNew("enable={0}", 1);
        List<BriChannel> briChannels = briChannelMapper.selectList(briChannelWrapper);
        if (briChannels != null && briChannels.size() > 0) {
            return briChannels.get(0);
        } else {
            return null;
        }
    }
}
